package com.dao;

import com.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author cyf
 * @description
 * @create 2018-09-10 13:56
 **/
@Repository
public class UserDao {

    private static final String MATCH_COUNT_SQL = "select count(*) COUNT from t_user t where t.user_name = ? and t.pass_word = ?";

    private static final String GET_USER_SQL = "select * from t_user t where t.user_name = ? ";

    private static final String UPDATE_LOGIN_SQL = "update t_user t set t.integral = ? , t.login_ip = ? , t.login_date = ? where t.user_id = ?";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     *  根据用户名和密码查询是否有对应用户存在
     * @param userName
     * @param passWord
     * @return
     */
    public int getMatchCount(String userName,String passWord){
        Map<String, Object> map = jdbcTemplate.queryForMap(MATCH_COUNT_SQL, new Object[]{userName, passWord});
        if(map.containsKey("COUNT")){
            return Integer.valueOf(map.get("COUNT").toString());
        }
        return 0;
    }

    /**
     * 根据用户名查询用户
     * @param userName
     * @return
     */
    public User getUserByUserName(final String userName){
        final User user = new User();
        jdbcTemplate.query(GET_USER_SQL, new Object[]{userName}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                user.setUserId(resultSet.getInt("user_id"));
                user.setUserName(userName);
                user.setIntegral(resultSet.getInt("integral"));
            }
        });
        return user;
    }

    /**
     *  更新登陆用户信息 修改积分 & 登陆IP & 登陆时间
     * @param user
     */
    public void updateLoginInfo(User user){
        jdbcTemplate.update(UPDATE_LOGIN_SQL,new Object[]{user.getIntegral(),user.getLoginIp(),user.getLoginDate(),user.getUserId()});
    }


}
